//给你一个二叉树的根结点 root ，请返回出现次数最多的子树元素和。如果有多个元素出现的次数相同，返回所有出现次数最多的子树元素和（不限顺序）。 
//
// 一个结点的 「子树元素和」 定义为以该结点为根的二叉树上所有结点的元素之和（包括结点本身）。 
//
// 
//
// 示例 1： 
//
// 
//
// 
//输入: root = [5,2,-3]
//输出: [2,-3,4]
// 
//
// 示例 2： 
//
// 
//
// 
//输入: root = [5,2,-5]
//输出: [2]
// 
//
// 
//
// 提示: 
//
// 
// 节点数在 [1, 10⁴] 范围内 
// -10⁵ <= Node.val <= 10⁵ 
// 
// Related Topics 树 深度优先搜索 哈希表 二叉树 👍 182 👎 0

package leetcode.editor.cn;

import java.util.*;

public class _508_MostFrequentSubtreeSum {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {
        Solution solution = new _508_MostFrequentSubtreeSum().new Solution();
//        TreeNode root = new TreeNode(5, new TreeNode(2), new TreeNode(-5));
        TreeNode root = new TreeNode(5, new TreeNode(2), new TreeNode(-3));
        int[] res = solution.findFrequentTreeSum(root);
        System.out.println(Arrays.toString(res));
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        HashMap<Integer, Integer> sumCount = new HashMap<>();
        public int[] findFrequentTreeSum(TreeNode root) {
            sum(root, 0);
            int maxCount = 0;
            for(int count : sumCount.values()) {
                maxCount = Math.max(maxCount, count);
            }
            List<Integer> list = new ArrayList<>();
            for (Map.Entry<Integer, Integer> entry : sumCount.entrySet()) {
                if (entry.getValue() == maxCount) {
                    list.add(entry.getKey());
                }
            }
            int[] res = new int[list.size()];
            for (int i = 0; i < list.size(); i++) {
                res[i] = list.get(i);
            }
            return res;
        }

        private int sum(TreeNode root, int sum) {
            if (root == null) {
                return sum;
            }
            int left = sum(root.left, sum);
            int right = sum(root.right, sum);
            int res = root.val + left + right;
            sumCount.put(res, sumCount.getOrDefault(res, 0) + 1);
            return res;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}